package com.gbx.sportsnews.fragments;


import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.gbx.sportsnews.BR;
import com.gbx.sportsnews.R;
import com.gbx.sportsnews.bean.GuessingEntity;
import com.gbx.sportsnews.databinding.FragmentGuessingBinding;
import com.gbx.sportsnews.service.NetService;
import com.gbx.sportsnews.utils.CommentRecyclerAdapter;

import java.util.ArrayList;
import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class GuessingFragment extends Fragment implements Callback<GuessingEntity> {


    private FragmentGuessingBinding binding;
    private CommentRecyclerAdapter<Object> adapter;
    private NetService service;
    private GuessingEntity body;

    public GuessingFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding= DataBindingUtil.inflate(inflater, R.layout.fragment_guessing, container, false);
        View view = binding.getRoot();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        HashMap<Class<?>, Pair<Integer, Integer>> map = new HashMap<>();
        map.put(null, Pair.create(R.layout.guessing_item, BR.contents));
        adapter = new CommentRecyclerAdapter<>(getContext(), new ArrayList<>(), map);
        binding.guessingRecycler.setAdapter(adapter);
        service = new Retrofit.Builder()
                .baseUrl("http://www.baidu.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(NetService.class);
        service.getGuess().enqueue(this);
    }

    @Override
    public void onResponse(Call<GuessingEntity> call, Response<GuessingEntity> response) {
        body=response.body();
        GuessingEntity.DataEntity data = body.getData();
        adapter.addAll(data.getContents());
    }

    @Override
    public void onFailure(Call<GuessingEntity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
